const simpleGit = require('simple-git');
const path = require('path');
require("dotenv").config();
const fs = require('fs').promises;

// 配置仓库路径
const repoPath = path.resolve(__dirname, './');
const git = simpleGit(repoPath);

// 从环境变量获取配置
const GIT_REPO_URL = process.env.GIT_REPO_URL;
console.log('Git Repo URL:', GIT_REPO_URL);
const GIT_USER_NAME = process.env.GIT_USER_NAME || 'Your Name';
console.log('Git User Name:', GIT_USER_NAME);
const GIT_USER_EMAIL = process.env.GIT_USER_EMAIL || 'your@email.com';
console.log('Git User Email:', GIT_USER_EMAIL);

async function setupGit() {
  try {
    // 确保目录存在
    try {
      await fs.access(repoPath);
      console.log(`Directory exists: ${repoPath}`);
    } catch (error) {
      console.log(`Directory ${repoPath} does not exist, creating...`);
      await fs.mkdir(repoPath, { recursive: true });
      console.log(`Created directory: ${repoPath}`);
    }

    // 初始化或检查仓库
    let isRepo = false;
    try {
      isRepo = await git.checkIsRepo();
    } catch (error) {
      if (error.message.includes('not a git repository')) {
        console.log('Initializing new Git repository...');
        await git.init();
        isRepo = true;
        console.log('Git repository initialized');
      } else {
        throw error;
      }
    }

    if (!isRepo) throw new Error('Failed to initialize repository');

    // 检查远程配置
    const hasRemote = await checkRemoteConfig();
    if (!hasRemote) {
      if (!GIT_REPO_URL) {
        throw new Error('GIT_REPO_URL environment variable is not set');
      }
      console.log(`Adding remote origin: ${GIT_REPO_URL}`);
      await addRemoteOrigin(GIT_REPO_URL);
    }

    return git;
  } catch (error) {
    console.error('Setup failed:', error.message);
    throw error;
  }
}

async function checkRemoteConfig() {
  try {
    const remotes = await git.getRemotes(true);
    const origin = remotes.find(r => r.name === 'origin');
    if (origin) {
      console.log('Remote origin URL:', origin.refs.fetch);
      return true;
    }
    return false;
  } catch (error) {
    console.log('No remote origin configured');
    return false;
  }
}

async function addRemoteOrigin(remoteUrl) {
  try {
    if (!remoteUrl.match(/^(https:\/\/|git@)/)) {
      throw new Error('Invalid Git repository URL format');
    }
    
    await git.addRemote('origin', remoteUrl);
    console.log(`Successfully added remote origin: ${remoteUrl}`);
    
    // 验证远程连接
    try {
      await git.fetch('origin');
      return true;
    } catch (verifyError) {
      await git.removeRemote('origin');
      throw new Error(`Failed to verify remote: ${verifyError.message}`);
    }
  } catch (error) {
    console.error('Failed to add remote:', error.message);
    throw error;
  }
}

async function ensureInitialCommit() {
  try {
    const log = await git.log();
    if (log.total === 0) {
      const readmePath = path.join(repoPath, 'README.md');
      await fs.writeFile(readmePath, '# Auto-generated Repository\n\nThis repository was automatically initialized.');
      await git.add('README.md');
      await git.commit('Initial commit');
      console.log('Created initial commit');
    }
  } catch (error) {
    console.error('Error ensuring initial commit:', error.message);
    throw error;
  }
}

async function pushChanges() {
  try {
    // 尝试推送
    const branches = await git.branchLocal();
    const currentBranch = branches.current;
    
    try {
      await git.push('origin', currentBranch);
      console.log(`Successfully pushed to ${currentBranch}`);
      return true;
    } catch (pushError) {
      // 如果是首次推送，需要设置上游分支
      if (pushError.message.includes('has no upstream branch')) {
        console.log('Setting upstream branch...');
        await git.push(['-u', 'origin', currentBranch]);
        console.log(`Successfully pushed and set upstream for ${currentBranch}`);
        return true;
      }
      throw pushError;
    }
  } catch (error) {
    console.error('Push failed:', error.message);
    throw error;
  }
}

async function main() {
  try {
    const git = await setupGit();
    
    // 配置用户信息
    await git.addConfig('user.name', GIT_USER_NAME);
    await git.addConfig('user.email', GIT_USER_EMAIL);
    
    // 确保有初始提交
    await ensureInitialCommit();
    
    // 添加所有文件
    await git.add('./*');
    
    // 检查是否有更改需要提交
    const status = await git.status();
    if (!status.isClean()) {
      const message = `Auto commit on ${new Date().toISOString()}`;
      await git.commit(message);
      console.log(`Committed changes: ${message}`);
      
      // 推送更改
      await pushChanges();
    } else {
      console.log('No changes to commit');
    }
    
    console.log('Git operations completed successfully');
  } catch (error) {
    console.error('Error:', error.message);
    process.exit(1);
  }
}

main();